using System;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.DAL;
using Core.Extentions;

namespace ScoutNET.Controllers
{
    public class ConvocController : ApplicationController
    {
        private SectionRepository sr = new SectionRepository();
        private ConvocRepository cr = new ConvocRepository();
        private NewsRepository nc = new NewsRepository();
        private MailToGenerateRepository mtgr = new MailToGenerateRepository();
        private CalendarRepository calr = new CalendarRepository();

        #region Properties
        private string MetaThumbnail { get { return ConfigurationManager.AppSettings["SiteUrl"] + "/Design/Images/TemplateSwitcher/logo.png"; } }
        #endregion

        #region View
        public ActionResult Index(string systemName)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName);
            ViewData["PageTitle"] = Resources.Convoc_Index_Title.Replace("[SECTION]", section.ToLower());
            ViewData["PageDescription"] = Resources.Convoc_Index_Description.Replace("[SECTION]", section.ToLower());
            ViewData["MetaThumbnail"] = this.MetaThumbnail;

            ViewData["SystemName"] = systemName;
            ViewData["SectionName"] = section;
            ViewData["UserType"] = UsersRepository.GetUserType(systemName);

            //Breadcrumb
            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Convoc_Index_Breadcrumb.Replace("[SECTION]", section.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            tSite_Convoc c = cr.GetCurrentConvocBySystemName(systemName);
            c = (c == null) ? cr.GetNextConvocBySystemName(systemName) : c;

            if (c != null)
            {
                ViewData["CurrentUrl"] = Server.UrlEncode(ConfigurationManager.AppSettings["SiteUrl"] + this.Url.RouteUrl(this.ControllerContext.RouteData.Values));
                ViewData["Convoc"] = c;
                ViewData["OtherConvoc"] = cr.GetConvocBySystemName(systemName, 0, 5, c.ID);
                return View("Index", c);
            }
            else
            {
                ViewData["OtherConvoc"] = cr.GetConvocBySystemName(systemName, 0, 5);
                ViewData["ErrorMessage"] = Resources.Convoc_Index_Error_NoConvoc.Replace("[SECTION]", section.ToLower());
                return View("Error");
            }
        }

        public ActionResult Detail(string systemName, int? id)
        {
            if (id != null)
            {
                tSite_Convoc c = cr.GetConvocByID((int)id);
                if (c != null)
                {
                    // Meta Tag
                    string section = sr.GetSectionNameBySystemName(systemName);
                    ViewData["PageTitle"] = Resources.Convoc_Detail_Title.Replace("[SECTION]", section.ToLower()).Replace("[STARTDATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[ENDDATE]", c.EndDate.ToString("dd/MM/yyyy"));
                    ViewData["PageDescription"] = Resources.Convoc_Detail_Description.Replace("[SECTION]", section.ToLower()).Replace("[STARTDATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[ENDDATE]", c.EndDate.ToString("dd/MM/yyyy"));
                    ViewData["MetaThumbnail"] = this.MetaThumbnail;

                    ViewData["SectionName"] = section;
                    ViewData["SystemName"] = systemName;
                    ViewData["UserType"] = UsersRepository.GetUserType(systemName);

                    //Breadcrumb
                    string[] saBreadcrumb = new String[2];
                    saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                    saBreadcrumb[1] = Resources.Convoc_Detail_Breadcrumb.Replace("[SECTION]", section.ToLower()).Replace("[STARTDATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[ENDDATE]", c.EndDate.ToString("dd/MM/yyyy"));
                    ViewData["Breadcrumb"] = saBreadcrumb;

                    ViewData["OtherConvoc"] = cr.GetConvocBySystemName(systemName, 0, 5, c.ID);
                    ViewData["Convoc"] = c;
                    ViewData["CurrentUrl"] = Server.UrlEncode(ConfigurationManager.AppSettings["SiteUrl"] + this.Url.RouteUrl(this.ControllerContext.RouteData.Values));

                    return View("Index", c);
                }
                else
                {
                    return View("Error404");
                }
            }
            else
            {
                return View("Error404");
            }
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Confirm()
        {
            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Create(string systemName)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(adminSection);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = adminSection });
            }

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = ut;

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Convoc_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Convoc_Create_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Convoc_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Convoc", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Convoc_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(string systemName, FormCollection fc)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(adminSection);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Create", new { systemName = systemName });
            }

            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Convoc_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Convoc_Create_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Convoc_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Convoc", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Convoc_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (ValidateNewConvoc(fc))
            {
                int sectionID = sr.GetSectionID(systemName);
                int resourceID = new Random().Next(1, 5);

                // Add convoc
                tSite_Convoc c = new tSite_Convoc();
                c.StartDate = DateTime.Parse(fc["StartDate"]);
                c.EndDate = DateTime.Parse(fc["EndDate"]);
                c.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                c.SID = sectionID;
                c.Convoc = Server.HtmlDecode(fc["Text"]).CleanWordTags();
                cr.InsertConvoc(c);
                cr.Save();

                string convocLink = Url.Action("Detail", new { controller = "Convoc", systemName = systemName, id = c.ID.ToString() });

                // Add News
                tSite_New n = new tSite_New();
                n.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                n.SID = sectionID;
                n.News = Server.HtmlDecode(GetNews(resourceID).Replace("[SECTION]", section).Replace("[INSERT_DATE]", DateTime.Now.GetNowTimeByTimeZone().ToString("dd/MM/yyyy")).Replace("[CONVOC_LINK]", convocLink));
                n.Title = Server.HtmlDecode(Resources.Convoc_Create_NewsTitle.Replace("[SECTION]", section).Replace("[INSERT_DATE]", DateTime.Now.GetNowTimeByTimeZone().ToString("dd/MM/yyyy")));
                nc.InsertNews(n);
                nc.Save();

                c.NID = n.ID;
                cr.Save();

                // Add user mail
                tMail_ToGenerate tg = new tMail_ToGenerate();
                tg.Action = this.ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
                tg.ItemID = c.ID;
                tg.SID = n.SID;
                tg.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                tg.ResourceID = resourceID;
                mtgr.InsertMail(tg);
                mtgr.Save();

                ViewData["ConvocID"] = c.ID;

                ViewData["ValidationMessage"] = Resources.Convoc_Create_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());
                return View("Validation");
            }
            else
            {
                return View();
            }
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Edit(string systemName, int id)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(adminSection);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Edit", new { systemName = adminSection });
            }

            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            // Meta Tag
            tSite_Convoc c = cr.GetConvocByID(id);
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Convoc_Edit_Title.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));
            ViewData["PageDescription"] = Resources.Convoc_Edit_Description.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Convoc_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Convoc", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Convoc_Edit_Breadcrumb.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));
            ViewData["Breadcrumb"] = saBreadcrumb;

            return View(c);
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(string systemName, int id, FormCollection fc)
        {
            // Redirect to admin section
            string adminSection = UsersRepository.GetAdminSection(systemName);
            UserType ut = UsersRepository.GetUserType(systemName);
            if (systemName != adminSection && ut != UserType.Administrator)
            {
                return RedirectToAction("Edit", new { systemName = adminSection });
            }

            ViewData["SystemName"] = systemName;
            ViewData["UserType"] = ut;

            // Meta Tag
            tSite_Convoc c = cr.GetConvocByID(id);
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Convoc_Edit_Title.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));
            ViewData["PageDescription"] = Resources.Convoc_Edit_Description.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Convoc_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Convoc", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Convoc_Edit_Breadcrumb.Replace("[START_CONVOC_DATE]", c.StartDate.ToString("dd/MM/yyyy")).Replace("[END_CONVOC_DATE]", c.EndDate.ToString("dd/MM/yyyy"));
            ViewData["Breadcrumb"] = saBreadcrumb;

            if (ValidateNewConvoc(fc))
            {
                ViewData["ValidationMessage"] = Resources.Convoc_Edit_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());
                ViewData["ConvocID"] = id;

                c.StartDate = DateTime.Parse(fc["StartDate"]);
                c.EndDate = DateTime.Parse(fc["EndDate"]);
                c.Convoc = Server.HtmlDecode(fc["Text"]).CleanWordTags();
                cr.Save();

                return View("Validation");
            }
            
            return View(c);
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Delete(string systemName, int id)
        {
            ViewData["ID"] = id.ToString();
           
            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        public EmptyResult Delete(string systemName, FormCollection fc)
        {
            int CID = -1;
            if (int.TryParse(fc["id"], out CID))
            {
                calr.RemoveConvocReference(CID);
                calr.Save();

                cr.Delete(CID);
                cr.Save();
            }

            return new EmptyResult();
        }
        #endregion

        #region Methodes
        private bool ValidateNewConvoc(FormCollection fc)
        {
            
            ModelState.SetModelValue("startdate", ValueProvider.GetValue("startdate"));
            ModelState.SetModelValue("enddate", ValueProvider.GetValue("enddate"));
            ModelState.SetModelValue("text", ValueProvider.GetValue("text"));
            
            DateTime startDate = new DateTime();
            DateTime endDate = new DateTime();

            if (!DateTime.TryParse(fc["startdate"], out startDate))
            {
                ModelState.AddModelError("startdate", Resources.Convoc_Create_Error_StartDate);
            }
            if (!DateTime.TryParse(fc["enddate"], out endDate))
            {
                ModelState.AddModelError("enddate", Resources.Convoc_Create_Error_EndDate);
            }
            if (startDate > endDate)
            {
                ModelState.AddModelError("_FORM", Resources.Convoc_Create_Error_Date);
                ModelState.AddModelError("startdate", string.Empty);
                ModelState.AddModelError("enddate", string.Empty);
            }
            if (String.IsNullOrEmpty(fc["text"]))
            {
                ModelState.AddModelError("text", Resources.Convoc_Create_Error_Text);
            }
            return ModelState.IsValid;
        }

        private string GetNews(int resourceId)
        {
            switch (resourceId)
            {
                case 1:
                    return Resources.Convoc_Create_NewsText1;
                case 2:
                    return Resources.Convoc_Create_NewsText2;
                case 3:
                    return Resources.Convoc_Create_NewsText3;
                case 4:
                    return Resources.Convoc_Create_NewsText4;
                default:
                    return Resources.Convoc_Create_NewsText5;
            }
        }
        #endregion
    }
}
